package com.healforce.medibasehealth.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.ansen.http.net.HTTPCaller;
import com.ansen.http.net.RequestDataCallback;

import com.healforce.medibasehealth.R;
import com.healforce.medibasehealth.bean.WeiXin;
import com.healforce.medibasehealth.bean.WeiXinInfo;
import com.healforce.medibasehealth.bean.WeiXinToken;
import com.healforce.medibasehealth.utils.Constant;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI wxAPI;
    private TextView tvNickname, tvAge;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);//注册

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        wxAPI = WXAPIFactory.createWXAPI(this, Constant.WECHAT_APPID, true);
        // 将应用的appId注册到微信
        wxAPI.registerApp(Constant.WECHAT_APPID);

        findViewById(R.id.btn_login).setOnClickListener(this);

        tvNickname = findViewById(R.id.tv_nickname);
        tvAge = findViewById(R.id.tv_age);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login://微信登录
                login();
                Log.e("zheng", "onClick: 微信");
                break;

        }
    }


    @Subscribe
    public void onEventMainThread(WeiXin weiXin) {
        Log.i("zheng", "收到eventbus请求 ---------------:" + weiXin.getCode());
        //登录
        getAccessToken(weiXin.getCode());

    }
    /**
     * 微信登陆(三个步骤)
     * 1.微信授权登陆
     * 2.根据授权登陆code 获取该用户token
     * 3.根据token获取用户资料
     */
    public void login() {

        if (!wxAPI.isWXAppInstalled()) {
            showToast("您还未安装微信客户端");
            return;
        }

        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = String.valueOf(System.currentTimeMillis());
        wxAPI.sendReq(req);

    }

    public void getAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + Constant.WECHAT_APPID + "&secret=" + Constant.WECHAT_SECRET +
                "&code=" + code + "&grant_type=authorization_code";
        HTTPCaller.getInstance().get(WeiXinToken.class, url, null, new RequestDataCallback<WeiXinToken>() {
            @Override
            public void dataCallback(WeiXinToken obj) {
                if (obj.getErrcode() == 0) {//请求成功
                    getWeiXinUserInfo(obj);
                } else {//请求失败
                    showToast(obj.getErrmsg());
                }
            }
        });
    }

    public void getWeiXinUserInfo(WeiXinToken weiXinToken) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                weiXinToken.getAccess_token() + "&openid=" + weiXinToken.getOpenid();


        HTTPCaller.getInstance().get(WeiXinInfo.class, url, null, new RequestDataCallback<WeiXinInfo>() {
            @Override
            public void dataCallback(WeiXinInfo obj) {
                tvNickname.setText("昵称:" + obj.getNickname());
                tvAge.setText("年龄:" + obj.getAge());
                Log.i("zheng", "头像地址:" + obj.getHeadimgurl());
            }
        });
    }


    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//取消注册
    }
}
